//1.二分 --- 二分查找
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int l = 0, r = n - 1;
        while(l <= r)
        {
            int mid = (l + r) >> 1;
            if(nums[mid] < target) l = mid + 1;
            else if(nums[mid] > target) r = mid - 1;
            else return mid;
        }
        return -1;
    }
};

//2.二分 --- 在排序数组中查找元素的第一个和最后一个位置
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n = nums.size();
        if(n == 0) return {-1, -1};
        //查找左端点
        int l = 0, r = n - 1;
        while(l < r)
        {
            int mid = (l + r) >> 1;
            if(nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        if(nums[l] != target) return {-1, -1};
        int tmp = l;
        
        //查找右端点
        l = 0, r = n - 1;
        while(l < r)
        {
            int mid = (l + r + 1) >> 1;
            if(nums[mid] > target) r = mid - 1;
            else l = mid;
        }
        return {tmp, l};
    }
};